#include <iostream>
#include <cstdio>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <cstdlib>
#include <string>
#include <string.h>
#include <arpa/inet.h>
#include <strings.h>
#include <unistd.h>
#include <pthread.h>
#include "Terimal.hpp"
using namespace std;

struct ThreadData
{
    int sockfd;
    struct sockaddr_in server;
    std::string ip;
};
void Usage(string proc)
{
    cout << "\n\r" << proc << " serverip serverport\n"
         << endl;
}
void *receiver(void *arg)
{
    //OpenTerimal();
    ThreadData *td = static_cast<ThreadData *>(arg);
    char buffer[1024];

    struct sockaddr_in temp;
    socklen_t len = sizeof(temp);
    while (true)
    {
        int s = recvfrom(td->sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &len);
        if (s > 0)
        {
            buffer[s] = 0;
            cerr << buffer << endl;
        }
    }
}
void *writer(void *arg)
{
    ThreadData *td = static_cast<ThreadData *>(arg);
    std::string welcom = td->ip;
    welcom += "commit.......";
    std::cerr << welcom << std::endl;
    string message;
    while (true)
    {
        cout << "please@";
        getline(cin, message);
        sendto(td->sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&(td->server), sizeof(td->server));
    }
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }

    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    ThreadData td;
    td.ip = serverip;
    // 1.创建套接字
    td.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (td.sockfd == -1)
    {
        perror("socket fail");
        exit(1);
    }
    bzero(&td.server, sizeof(td.server));
    td.server.sin_family = AF_INET;
    td.server.sin_port = htons(serverport);
    td.server.sin_addr.s_addr = inet_addr(serverip.c_str());

    pthread_t r;
    pthread_t w;
    pthread_create(&r, nullptr, receiver, &td);
    pthread_create(&w, nullptr, writer, &td);

    pthread_join(r, nullptr);
    pthread_join(w, nullptr);

    close(td.sockfd);
    return 0;
}